<template>
  <div class="purse">
    <div class="purse-header">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/user/home/menu' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>我的钱包</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="purse-main clearfloat">
      <div class="main_left fl">
        <div class="user_info">
          <el-avatar :size="70" :src="baseUrl + '/storage/upload/' + $store.state.user.img"></el-avatar>
          <template v-if="$store.state.user.vip">
            <template v-if="$store.state.user.vip">
              <div class="info-vip">
                <el-popover
                  placement="right"
                  title="当前会员等级权益"
                  width="300"
                  trigger="hover"
                  v-if="$store.state.user.vip != 0"
                >
                  <div class="vip_Introduction">
                    <ul>
                      <li>
                        <span>1，可享受撰写案件上报国知局后缴纳专利代理费和官费。</span>
                      </li>
                      <!-- <li>
                        <span>2，可享受提交订单后优先分配代理人特权。</span>
                      </li>
                      <li>
                        <span>3，可享受免技术交底文件撰写案件。</span>
                      </li> -->
                      <li>
                        <span>
                          2，有权参加本系统推出的积分兑换现金的活动，
                          <font class="font_success">{{vipLevelTips.minPoints}}</font>积分起兑
                        </span>。
                      </li>
                      <li>
                        <span>
                          3，
                          <font class="font_success">1</font>积分可兑换
                          <font class="font_success">{{ vipLevelTips.Points }}</font>元
                        </span>。
                      </li>
                    </ul>
                  </div>
                  <i slot="reference" class="el-icon-info orange ml10"></i>
                </el-popover>
              </div>
            </template>
            <!-- <div class="expire" v-if="$store.state.user.vip_expire_time.length > 0">
              <span>到期时间：</span>
              <span>{{ $store.state.user.vip_expire_time | formatTime}}</span>
            </div> -->
            <!-- <el-button class="renewal" @click="buyVip">续费</el-button> -->
          </template>
          <!-- <div v-else>
            <el-button type="primary" class="upgradeVIP">升级VIP</el-button>
          </div> -->
          <div class="money">
            <div class="frozenCoin clearfloat">
              <span class="label">冻结金额:</span>
              <span>{{frozenBalance}}元</span>
              <el-popover placement="right" title="金额说明" width="300" trigger="hover">
                <div class="vip_Introduction">
                    <ul>
                      <li>
                        <span>1，冻结金额只能支付订单，无法体现到银行卡！</span>
                      </li>
                      <li>
                        <span>2，余额提现到银行卡将收取0.6%的手续费</span>
                      </li>
                      <li>
                        <span>3，充值成功后，增加积分，充值金额可在消费时直接抵扣！</span>
                      </li>
                    </ul>
                </div>
                <i slot="reference" class="el-icon-info orange fr"></i>
              </el-popover>
            </div>
            <div class="coin clearfloat">
              <span class="label">我的余额:</span>
              <span>{{balance}}元</span>
              <el-button class="invest-btn fr" @click="recharge">充值</el-button>
              <el-button class="cashing-btn fr" @click="withdraw('balance')">提现</el-button>
            </div>
          </div>
          <div class="money">
            <div class="frozenCoin clearfloat">
              <span class="label">冻结积分:</span>
              <span>{{frozenPoints}}分</span>
            </div>
            <div class="coin clearfloat">
              <span class="label">我的积分:</span>
              <span>{{points}}分</span>
              <el-button class="cashing-btn fr" @click="withdraw('points')">兑换</el-button>
            </div>
          </div>
        </div>
        <!-- vip 图标 -->
        <img src="../../../assets/img/V.png" alt />
      </div>
      <div class="main_right fr">
        <div class="herder clearfloat">
          <span class="title fl">我的余额明细</span>
          <div class="fr btns">
            <el-select
              v-model="purseDetailTypes"
              multiple
              collapse-tags
              @change="purseQueryTypes"
              placeholder="选择明细类型查询"
            >
              <el-option
                v-for="item in purseDetailTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-date-picker
              v-model="createdTime"
              unlink-panels
              type="daterange"
              range-separator="至"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              start-placeholder="开始日期"
              @change="confirmQuery"
              end-placeholder="结束日期"
            ></el-date-picker>
          </div>
        </div>
        <el-table
          :data="balanceDetails"
          ref="table"
          height="250"
          stripe
          border
          infinite-scroll-delay="1000"
          infinite-scroll-immediate="false"
          infinite-scroll-disabled="disabled"
          style="width: 100%"
        >
          <el-table-column prop="payMethod" label="编号" align="center" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ scope.row.number }}
            </template>
          </el-table-column>
          <el-table-column prop="type" label="明细类型" align="center">
            <template slot-scope="scope">{{ scope.row.type | userPurseType }}</template>
          </el-table-column>
          <el-table-column prop="money" align="center" label="金额">
            <template slot-scope="scope">
              <span
                :class="scope.row.money >= 0 ? 'font_success' : 'font_danger'"
              >{{ scope.row.money > 0 ? `+${scope.row.money}` : scope.row.money}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" align="center" label="时间" :show-overflow-tooltip="true">
            <template slot-scope="scope">{{ scope.row.created_at}}</template>
          </el-table-column>
        </el-table>
        <div class="herder clearfloat">
          <span class="title fl">我的积分明细</span>
          <div class="fr btns">
            <el-select
              v-model="pointsDetailTypes"
              multiple
              collapse-tags
              @change="pointsQueryTypes"
              placeholder="选择明细类型查询"
            >
              <el-option
                v-for="item in pointsDetailTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-date-picker
              v-model="pointsCreatedTime"
              unlink-panels
              type="daterange"
              range-separator="至"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              start-placeholder="开始日期"
              @change="confirmQuery('points')"
              end-placeholder="结束日期"
            ></el-date-picker>
          </div>
        </div>
        <!-- 
        v-infinite-scroll="load"-->
        <el-table
          :data="pointsDetails"
          ref="table2"
          height="250"
          stripe
          border
          infinite-scroll-delay="1000"
          infinite-scroll-immediate="false"
          infinite-scroll-disabled="disabled"
          style="width: 100%"
        >
          <el-table-column prop="payMethod" label="编号" align="center" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ scope.row.number }}
            </template>
          </el-table-column>
          <el-table-column prop="type" label="明细类型" align="center">
            <template slot-scope="scope">{{ scope.row.type | userPursePointsType }}</template>
          </el-table-column>
          <el-table-column prop="points" align="center" label="积分">
            <template slot-scope="scope">
              <span
                :class="scope.row.points >= 0 ? 'font_success' : 'font_danger'"
              >{{ scope.row.points > 0 ? `+${scope.row.points}` : scope.row.points}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" align="center" label="时间" :show-overflow-tooltip="true">
            <template slot-scope="scope">{{ scope.row.created_at}}</template>
          </el-table-column>
        </el-table>
      </div>
      <!-- <div class="main_right fr">
        
      </div> -->
    </div>
    <withdrawDialog ref="withdrawDialog" @refresh="refresh"></withdrawDialog>
    <rechargeDialog ref="rechargeDialog" @refresh='refresh'></rechargeDialog>
    <buyVipDialog ref="buyVipDialog" @refresh='refresh'></buyVipDialog>
  </div>
</template>

<script>
import moment from "moment";
import QRCode from "qrcode"; // 引入qrcode
import aes from "~/util/aes.js";
import rechargeDialog from './components/recharge-dialog'
import withdrawDialog from "./components/withdrawDialog";
import buyVipDialog from './components/buyVIp-diaglog'
import { pointsTypeOptions, purseTypeOptions } from "./components/config";
export default {
  data() {
    return {
      baseUrl: global.baseurl,
      purseDetailTypeOptions: purseTypeOptions,
      purseDetailTypes: "",
      pointsDetailTypeOptions: pointsTypeOptions,
      pointsDetailTypes: "",
      vipLogo: "",
      vipLevelTips: {
        Points: "",
        minPoints: ""
      },
      balanceDetails: [],
      pointsDetails: [],
      createdTime: [],
      pointsCreatedTime: [],
      paramsByPurse: {
        is_frozee: 0,
        type: "0,1,2,3,4,5,6,7,8,9,10"
      },
      paramsByPoints: {},
      points: "", // 积分
      frozenPoints: "", // 冻结积分
      balance: null, // 余额
      frozenBalance: null, // 冻结余额
      qrcodeURL: `http://m.mingyukehui.com/register?channel_pid=${this.$store.state.user.cryptId}&code=${this.$store.state.user.invitation_code}`,
      pcQrcodeURL: `http://mingyukehui.com/register?channel_pid=${this.$store.state.user.cryptId}&code=${this.$store.state.user.invitation_code}`,
      vipLogoClass: "",
      noMore:false,
      page: 1,
      dom: null,
    };
  },
  components: {
    withdrawDialog,
    rechargeDialog,
    buyVipDialog
  },
  mounted() {
    // 创建二维码
    this.createQrCode("qrcode", this.qrcodeURL)
    // 获取需要绑定的table
    this.dom = this.$refs.table.bodyWrapper
    this.dom.addEventListener('scroll', () => {
      // 滚动距离
      let scrollTop = this.dom.scrollTop
      // 变量windowHeight是可视区的高度
      let windowHeight = this.dom.clientHeight || this.dom.clientHeight
      // 变量scrollHeight是滚动条的总高度
      let scrollHeight = this.dom.scrollHeight || this.dom.scrollHeight
      if (scrollTop + windowHeight === scrollHeight) {
        // 获取到的不是全部数据 当滚动到底部 继续获取新的数据

        if (!this.noMore) {
          this.load()
        }
      }
    })
  },
  watch: {
    "$store.state.user.vip": {
      handler: function(val) {
        if (val == 0) {
          this.vipLogoClass = "icon iconfont icon-VIP";
        } else if (val == 1) {
          this.vipLogoClass = "icon iconfont icon-vip1 font_red";
          this.vipLevelTips.Points = 1;
          // this.vipLevelTips.minPoints = 200
        } else if (val == 2) {
          this.vipLogoClass = "icon iconfont icon-vip2 font_red";
          this.vipLevelTips.Points = 3;
          // this.vipLevelTips.minPoints = 500
        } else if (val == 3) {
          this.vipLevelTips.Points = 5;
          this.vipLogoClass = "icon iconfont icon-vip3 font_red";
          // this.vipLevelTips.minPoints = 1000
        } else if (val == 4) {
          this.vipLogoClass = "icon iconfont icon-vip4 font_red";
          this.vipLevelTips.Points = 10;
          // this.vipLevelTips.minPoints = 2000
        }
      },
      immediate: true
      // deep: true
    },
    createdTime: {
      handler: function(val) {
        if (val && val.length > 0) {
          this.paramsByPurse.start_time = val[0];
          this.paramsByPurse.end_time = val[1];
        }
      },
      deep: true
    },
    pointsCreatedTime: {
      handler: function(val) {
        if (val && val.length > 0) {
          this.paramsByPoints.start_time = val[0];
          this.paramsByPoints.end_time = val[1];
        }
      },
      deep: true
    }
  },
  created() {
    // 默认查询当月明细
    // let nowTiem = {
    //   start_time: `${moment().format("YYYY-MM")}-01`,
    //   end_time: `${moment().format("YYYY-MM")}-31`
    // };
    let nowTiem = {
      start_time: '',
      end_time: ''
    };
    this.createdTime[0] = nowTiem.start_time;
    this.createdTime[1] = nowTiem.end_time;
    this.paramsByPurse.start_time = nowTiem.start_time;
    this.paramsByPurse.end_time = nowTiem.end_time;
    this.paramsByPoints.start_time = nowTiem.start_time;
    this.paramsByPoints.end_time = nowTiem.end_time;
    this.getDetailsData(nowTiem);
    this.getPointsDetails(nowTiem);
    this.queryBalance();
    this.queryIntegral();

    this.getWithdrawalAmount();
  },

  methods: {
    // renewal() {
    //   // 购买vip
    //   this.$router.replace({
    //     name: "payment",
    //     query: {
    //       type: "buyVip",
    //       vip: btoa("vip1"),
    //       from: this.$route.path
    //     }
    //   });
    // },
    // 购买vip
    buyVip () {
      this.$refs['buyVipDialog'].show()
    },
    // 获取vip配置
    getWithdrawalAmount() {
      this.$axios
        .get("api/activity/consumer_setting")
        .then(res => {
          if (res.data.code == 200) {
            if (this.$store.state.user.vip != 0) {
              this.vipLevelTips.minPoints =
                res.data.data[`vip${this.$store.state.user.vip}`].min;
            }
          }
        })
        .catch(error => {
          this.$message.error(error);
        });
    },

    // 查看冻结金额明细
    showFrozee() {
      this.$refs["frozeeDetail"].show(this.createdTime);
    },
    purseQueryTypes(value) { 
      console.log(value)
      if (value) {
        if(value == 8){
          this.paramsByPurse.type = '8,9,10';
          this.paramsByPurse.page = 1
        }else{
          this.paramsByPurse.type = value.join(",");
          this.paramsByPurse.page = 1
        }
      } else {
        this.paramsByPurse.type = "0,1,2,3,4,5,6,7,8";
      }
      this.getPointsDetails(this.paramsByPurse);
    },
    pointsQueryTypes(value) {
      this.paramsByPoints.type = value.join(",");
      this.getDetailsData(this.paramsByPoints);
    },
    // 购买vip
    buyVip() {
      this.$refs["buyVipDialog"].show();
    },
    // 充值
    recharge() {
      this.$refs["rechargeDialog"].show();
    },
    refresh() {
      this.getDetailsData();
      this.getPointsDetails();
      this.queryBalance();
      this.queryIntegral();
    },
    // 获取积分明细数据
    getDetailsData(pParams) {
      let params = {};
      if (pParams) {
        params = pParams;
      }
      params.is_all = 1;
      console.log(params)
      this.$axios
        .get("api/drawing/wallet/consumer_points_detail", {
          params: params
        })
        .then(res => {
          this.pointsDetails = res.data.data;
        });
    },
    // 获取余额明细数据
    getPointsDetails(pParams, scrollData) {
      let params = {};
      if (pParams) {
        params = { ...params, ...pParams, ...this.paramsByPurse };
      }
      params.is_all = 0;
      this.$axios
        .get("api/drawing/wallet/consumer_detail", {
          params: params
        })
        .then(res => {
          if (res.data.code == 200) {

            if (scrollData) {
              let data = res.data.data
              if (data.length == 0) {
                this.noMore = true
              }
              this.balanceDetails = this.balanceDetails.concat(data)
            } else {
              this.balanceDetails = res.data.data
              this.dom.scrollTop = this.dom.scrollTop - 100
            }
          } else {
            this.$message.error(res.data.message)
          }
        })
    },
    load() {
      this.page ++
      this.paramsByPurse.page = this.page
      this.getPointsDetails(this.paramsByPurse, true)
    },
    // 获取余额
    queryBalance() {
      this.$axios.get("api/drawing/consumer_wallet").then(res => {
        if (res.data.code == 200) {
          this.balance = res.data.data.coin;
          this.frozenBalance = res.data.data.frozenCoin;
        } else if (res.data.code == 400) {
          this.$message.error(res.data.message);
        }
      });
    },
    // 获取积分
    queryIntegral() {
      this.$axios.get("api/drawing/consumer").then(res => {
        if (res.data.code == 200) {
          this.points = res.data.data.points;
          this.frozenPoints = res.data.data.frozenPoints;
        } else if (res.data.code == 400) {
          this.$message.error(res.data.message);
        }
      });
    },

    // 发起提现申请
    withdraw(type) {
      let data = {};
      if (type == "balance") {
        this.queryBalance();
        data = {
          points: this.balance,
          frozenPoints: this.frozenBalance,
          type: "balance"
        };
      } else {
        this.queryIntegral();
        data = {
          points: this.points,
          frozenPoints: this.frozenPoints,
          type: "points"
        };
      }
      this.$refs.withdrawDialog.show(data); 
    },

    // 时间查询
    confirmQuery(type) {
      if (type == "points") {
        if (this.pointsCreatedTime) {
          this.paramsByPoints.start_time = this.pointsCreatedTime[0];
          this.paramsByPoints.end_time = this.pointsCreatedTime[1];
          this.getDetailsData(this.paramsByPoints);
        } else {
          this.getDetailsData();
        }
      } else {
        if (this.createdTime) {
          this.paramsByPurse.start_time = this.createdTime[0];
          this.paramsByPurse.end_time = this.createdTime[1];
          this.getPointsDetails(this.paramsByPurse);
        } else {
          this.getPointsDetails();
        }
      }
    },

    createQrCode(refName, payUrl) {
      QRCode.toDataURL(this.$refs[refName], payUrl, {
        width: 120,
        height: 120
      })
        .then(url => {})
        .catch(err => {
          // this.openMessage(0, '生成二维码失败')
        });
    },
    // 复制成功
    onCopy(e) {
      this.$message({
        message: "复制成功！",
        type: "success"
      });
    },
    // 复制失败
    onError(e) {
      this.$message({
        message: "复制失败！",
        type: "error"
      });
    }
  }
};
</script>

<style lang='less'>
.purse {
  width: 90%;
  height: 100%;
  min-height: 750px;
  padding: 30px;
  margin: 0 auto;
  box-sizing: border-box;
  background: rgba(255, 255, 255, 1);
  &-header {
    height: 45px;
    .el-breadcrumb {
      .el-breadcrumb__item {
        .el-breadcrumb__inner,
        .el-breadcrumb__separator {
          font-size: 25px;
          color: rgba(0, 35, 151, 1);
          font-weight: 400;
        }
      }
      .el-breadcrumb__item:first-child {
        .el-breadcrumb__inner {
          padding-left: 10px;
          border-left: 5px solid #002397;
        }
      }
    }
    border-bottom: 2px solid #e5e5e5;
    box-sizing: border-box;
  }

  &-main {
    margin-top: 30px;
    width: 100%;
    box-sizing: border-box;
    height: calc(100% - 75px);
    .main_left {
      width: 300px;
      height: 100%;
      background: linear-gradient(
        0deg,
        rgba(117, 185, 255, 1) 0%,
        rgba(22, 137, 255, 1) 100%
      );

      .user_info {
        height: 400px;
        box-sizing: border-box;
        padding-top: 40px;
        .el-avatar {
          margin: 0 auto;
          display: block;
        }

        .info-vip {
          height: 28px;
          width: 29px;
          margin: 17px auto 0;
          background: url("../../../assets/img/图标.png") no-repeat;
          background-position: -94px -32px;
          position: relative;
          .el-icon-info {
            position: absolute;
            right: -20px;
            top: 8px;
          }
        }
        .expire {
          font-size: 12px;
          color: rgba(255, 255, 255, 1);
          margin: 12px auto 0;
          width: 130px;
          text-align: center;
        }
        .upgradeVIP {
          padding: 7px 24px 7px 23px;
          background: #0090ff;
          display: block;
          margin: 17px auto 0;
          border-radius: 0px;
        }
        .renewal {
          font-size: 12px;
          padding: 4px 18px;
          background: #ffa200;
          border-radius: 10px;
          margin: 11px auto 0;
          display: block;
          border-color: #ffa200;
          color: #fff;
        }
        .money {
          height: 90px;
          width: 270px;
          margin: 20px auto 0;
          padding: 20px 8px 0px 8px;
          border-top: 1px solid rgba(255, 255, 255, 1);
          box-sizing: border-box;

          .frozenCoin {
            font-size: 14px;
            color: #fc8200;
          }
          .coin {
            font-size: 15px;
            color: #002d88;
            line-height: 17px;
            margin-top: 5px;

            .cashing-btn {
              font-size: 12px;
              padding: 3px 9px;
              background: #2368b0;
              border-radius: 10px;
              border-color: #2368b0;
              color: #fff;
            }
            .invest-btn {
              font-size: 12px;
              padding: 3px 9px;
              border-radius: 10px;
              border-color: #ffa200;
              color: #fff;
              background: #ffa200;
            }
          }
          .label {
            color: #fff;
          }
        }
      }
      // .background {
      //   height: calc(100% - 440px);
      //   background: url('../../../assets/img/V.png') no-repeat;
      // }
    }

    .main_right {
      width: calc(100% - 300px);
      height: 100%;
      padding: 0 0 0 27px;
      display: flex;
      flex-direction: column;
      margin-bottom: 20px;

      .herder {
        min-height: 60px;
        width: 100%;

        .title {
          display: inline-block;
          padding-top: 12px;
          font-size: 20px;
          color: rgba(72, 72, 72, 1);
          margin-bottom: 10px;
        }
        .btns {
          // margin-top: 10px;
        }
        .el-select {
          margin-right: 10px;
          margin-bottom: 10px;
        }
        .el-range-editor {
          margin-bottom: 10px;
        }
      }
      .el-table {
        margin-bottom: 10px;
      }
    }
  }
}
.vip_Introduction {
  margin-top: 10px;
  ul {
    padding-left: 10px;
    li {
      list-style: none;
      span {
        font-size: 14px;
      }
    }
  }
}
</style>